package net.gpai.tool

import net.coobird.thumbnailator.Thumbnails
import net.gpai.logger.logger
import java.io.File
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import javax.imageio.ImageIO

private val log = logger("Util")

/**
 * 返回处理后文件的根目录
 */
fun compressImages(images: List<File>, outputQuality: Float = 100f, prefix: String): CompressResult {
    val compressResult = CompressResult()
    if (images.isEmpty()) {
        return compressResult
    }

    val baseDir = images.first().parentFile.path + "${File.separator}压缩${
        LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
    }"
    // 创建目录
    File(baseDir).mkdirs()

    compressResult.baseDir = baseDir

    for (index in images.indices) {
        val i = index + 1
        val file = images[index]
        try {
            val suffixName = file.name.substringAfterLast(".")
            log.debug("文件编号:$i,文件路径:${file.path},文件扩展名:${suffixName}")
            val fileName = if (prefix != "" && prefix.trim() != "") {
                "$prefix$i.$suffixName"
            } else {
                "${file.name}"
            }
            compress(file, outputQuality, File(baseDir, fileName))
        } catch (e: Exception) {
            log.error("文件处理失败:file:{}", file.path, e)
            val hashMap = HashMap<String, Any>()
            hashMap["file"] = file.name
            hashMap["error"] = "处理失败:${e.message}"
            compressResult.errorItem.add(hashMap)
        }
    }
    return compressResult
}


/**
 * 传入一个File,调用Thumbnails进行压缩
 * @param file 要压缩的图片源文件
 * @param outputQuality 压缩质量 1-100
 * @param outputFile 输出文件路径
 */
private fun compress(file: File, outputQuality: Float = 100f, outputFile: File) {
    val image = ImageIO.read(file) ?: throw RuntimeException("image is null")
    if (image.width > 1000) {
        Thumbnails.of(file).width(1000).outputQuality(outputQuality / 100).toFile(outputFile)
        return
    } /*else if (image.height > 3000) {
        Thumbnails.of(file).height(3000).outputQuality(outputQuality / 100).toFile(outputFile)
        return
    } */else {
        // 不大于1000的图直接原比例压缩一次
        Thumbnails.of(file).width(image.width).outputQuality(outputQuality / 100).toFile(outputFile)
    }
}

class CompressResult {
    // 处理后的根目录
    var baseDir: String = ""

    // 处理失败的项目
    var errorItem: ArrayList<Map<String, Any>> = ArrayList()

    fun getErrorInfo(): String {
        return errorItem.toString()
    }
}